/**
 * Copyright 2009 Erick Armbrust 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0 
 *   
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */

package tapioca.dt;

/**
 * An enum representing the possible states of a distributed transaction that is currently in
 * progress.  These enums are "ranked" to restrict the possible state transitions.  Progress from
 * one state to the next can move forward, but not laterally within a given ranking.
 *
 * @author armbrust@gmail.com (Erick Armbrust)
 */
public enum State {
  INIT_0(0), 
  READY_1(1), 
  LOCKED_2(2),
  CHECKED_3(3),
  ABORTING_3(3),
  DONE_4(4),
  ABORTED_4(4);
  
  private final int ranking;
  
  /**
   * Constructor.
   * 
   * @param ranking the rank of the state.
   */
  private State(int ranking) {
    this.ranking = ranking;
  }
  
  public int getRanking() {
    return ranking;
  }
  
  @Override
  public String toString() {
    String[] tokens = super.toString().toLowerCase().split("_");
    return tokens[1] + tokens[0];
  }
  
  /**
   * Converts the string representation of a state enum to an enum value.  This should be used
   * instead of {@code State.valueOf(string)} since the string representation has been customized. 
   * 
   * @param value the string value to convert to a State enum.
   * @return the State enum corresponding to the given string.
   */
  public static State getValue(String value) {
    String convertedValue = value.substring(1).toUpperCase() + "_" + value.substring(0, 1);
    return valueOf(convertedValue);
  }
  
}
